
//更新debit 和credit的汇总栏位
function refreshSummary() {

  var debit = getDebit()
  var credit = getCredit()
  var summary = summarizeDebitCredit(debit, credit)

  $("#debit_sum").html(summary[0])
  $("#credit_sum").html(summary[1])

}
/*
function clickButton() {
    alert('点击button了')
}
 */
function addVoucherElement() {
  $("#tbody_voucher").append(generateVoucherElement())
  enableVoucherSummaryAutoComplete(availableSummaryTitle)
  enableDebitCreditSummary()
  //enableTooptip()
  $("#delete_element_" + voucherelement_sn).tinyTips('light', 'title')

}

function generateVoucherElement() {
  voucherelement_sn = voucherelement_sn + 1;  //init a serial sn
  var element_str = "<tr align='center' id='tr_element_" + voucherelement_sn + "'>"
  element_str += "<td><input type='text' id='voucher_summary_" + voucherelement_sn + "' name='voucher[][summary]' class='validate[length[0,100]]' /></td>"
  //element_str += "<td><input type='text' id='voucher_subject_" + voucherelement_sn + "' name='voucher[][subject]' class='validate[funcCall[validateDebitCredit]]'  /></td>"
  element_str += "<td><select style='width:280px;' id='voucher_subject_" + voucherelement_sn + "' name='voucher[][subject]' class='validate[funcCall[validateDebitCredit]]' ><option></option>" + subject_options + "</select></td>"
  element_str += "<td><input size='10' type='text' id='voucher_debit_" + voucherelement_sn + "' name='voucher[][debit]' class='validat[funcCall[validateDebitCredit],custom[validNumber]]' /></td>"
  element_str += "<td><input size='10' type='text' id='voucher_credit_" + voucherelement_sn + "' name='voucher[][credit]' class='validat[funcCall[validateDebitCredit],custom[validNumber]]' /></td>"
  element_str += "<td><img src='/images/icons/delete.png' onClick='deleteElement(\"tr_element_" + voucherelement_sn + "\")' id='delete_element_" + voucherelement_sn + "' title='点击此处删除该行'></td>"
  element_str += "</tr>"
  return element_str;

}

function validateDebitCredit() {
  var debit = getDebit()
  var credit = getCredit()
  //检查表单的借贷输入
  if(! validateDebitCreditInput(debit, credit) ) {
    return true
  }
  return false
}

//激活借贷栏位的汇总
function enableDebitCreditSummary() {

  $("input[id*=voucher_debit]").change(function(){
    refreshSummary()
  })
  $("input[id*=voucher_credit]").change(function(){
    refreshSummary()
  })
}

function enableFormValidationEngine() {

  $("#form_voucher").validationEngine({
    //如果form自身的检验成功,对表单整体进行效验
    success: function() {
      checkForm()
      },
    //如果失败弹出错误对话框
    failure: function(){
      showErrorDialog("您的表单输入有错误,请修正后重试.")
      }
  })
}

//对表单进行全面检查。
function checkForm() {

  var debit = getDebit()
  var credit = getCredit()
  var summary = getSummary()  //取摘要
  var subject = getSubject()  //取科目代码
  var voucher_date = $("#voucher_date").val()
  var error = 0
  var error_msg = ''
  //检查是否表单是空的

  //借贷汇总是否为0,为0的话表示借贷栏位都为空，报错
  var summarizedDebitCredit = summarizeDebitCredit(debit, credit)
  if((summarizedDebitCredit[0] == 0) && (summarizedDebitCredit[1] == 0 ) ) {
    error += 1
    error_msg += "借贷金额栏位必须填写"
  }

  //alert("现在对整表进行检查")
  //检查借贷栏目的填写
  if(! validateDebitCreditInput(debit, credit)){
    error += 1
    error_msg += "借贷金额填写有误，请修改正确后重试。<br />"
  }
  //检查借贷是否平衡
  if(! validateDebitCreditBalance(debit, credit)) {
    error += 1
    error_msg += "借贷金额总计不相同，请修改正确后重试。<br />"
  }

  //检查摘要栏位是否填写正确
  if(! validateVoucherFormInput(summary, subject, debit, credit) ){
    error += 1
    error_msg += "表单检验出错，请确认栏位填写正确。<br />"
  }
  //重新激活表单校验
  enableFormValidationEngine()

  if(error) {
    showErrorDialog(error_msg,"表单校验出错")
  } else {
    //校验成功,弹出确认对话框
    //alert('校验成功,进行确认')
    showConfirmDialog('您确定要对填写的内容进行保存吗?','保存?', saveForm)
  }

}

function saveForm() {
  var debit = getDebit()
  var credit = getCredit()
  var summary = getSummary()
  var subject = getSubject()
  //将数组转成string $.JSON.encode(array). 将字串转成json: $.JSON.decode(str)
  var poststr = "{"
  poststr += "debit:" + $.JSON.encode(debit)
  poststr += ",credit:" + $.JSON.encode(credit)
  poststr += ",summary:" + $.JSON.encode(summary)
  poststr += ",subject:" + $.JSON.encode(subject)
  poststr += ",acct_set_id:" + $("input[name=acct_set_id]").val()
  poststr += ",voucher_date:'" + $("input[name=voucher_date]").val() + "'"
  poststr += "}"
  var postdata = $.JSON.decode(poststr) //将string转成json
  //通过ajax提交表单
    
  $.ajax({
    url: $("#form_voucher").attr("action"),
    data: postdata,
    type: "post",
    beforeSend: function() {
      closeAllErrorBar()
      //显示loading bar modal
      $('body').block({
        theme: true,
        message:'<br /><img src="/images/loadingAnimation.gif"><br />\
                      程序正在执行您请求的操作<br />请稍候片刻...<br />'
      })
    },
    success: function(data){
      //display next to do dialog
      var dialog = generateConfirmDialog('您的资料已成功添加');
      $("body").append(dialog[1])

      $("#" + dialog[0]).dialog({
        resizable: false,
        height:140,
        modal: true,
        closeOnEscape: false,
        /*open: function(event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        },*/
        buttons: {
          '返回': function() {
            window.location.href = "../"
            $(this).dialog('destroy')
          },
          '继续添加': function() {
            window.location.reload()
            $(this).dialog('destroy')
          }
        }
      });
    },
    complete: function() {
      $('body').unblock()
    },
    error: function() {
      showErrorDialog('会计凭证保存出错，可能是网络不稳定或服务器连接错误，请重试．．．')
      showErrorBar('会计凭证保存出错，可能是网络不稳定或服务器连接错误，请重试．．．')
    }
  })
    
//alert('Now Saving Form')
}

function generateWhatToDoNextDialog(msg, title){

  title  = typeof(title) != 'undefined' ? title : '请选择您要进行的操作'
  msg = typeof(msg) != 'undefined' ? msg : "您所输入的资料已经成功添加．";
  var uniquestamp = generateUniqueStamp()
  //create the unique div id
  var div_id = "dialog_next2do_" + uniquestamp;

  var dialog_str = "<div id='" + div_id + "' title='" + title + "' style='display:none'>"
  //dialog_str += "<div id='dialog-confirm' title='" + title + "'>"
  dialog_str += "<p><span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>"
  dialog_str += msg
  dialog_str += "</p>"
  dialog_str += "<p><input type='button' id='btn_back' value='返回' />&nbsp;"
  dialog_str += "<input type='button' id='btn_continue' value='继续添加' /></p>"
  dialog_str += "</div>"
  //dialog_str += "</div>"

  return new Array(div_id, dialog_str)

}

/* 通过css实现了对jquery ui窗口中关闭按钮的隐藏，故不再需要该函数来生成“下一步”对话框 */
function showWhatToDoNextDialog(msg, title) {
  var dialog = generateWhatToDoNextDialog(msg,title)
  $.blockUI({
    message: $("#" + dialog[1]),
    theme:true
  })
  $(document).ready(function(){
    $("#" + dialog[0] + " #btn_back").click(function(){
      window.location.href = "../"
    })
    $("#" + dialog[0] + " #btn_continue").click(function(){
      window.location.reload()
    })
  })
}
